package com.springcloud.commom.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;


/**申明是个切面*/
@Aspect
///**申明是个组件*/
@Component
///**标记定义了优先顺序。*/
@Order(1)
public class AopLogAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ObjectMapper objectMapper;

    //申明一个切点 里面是 execution表达式
    @Pointcut("execution(public * com..*.*controller*..*(..))")
    public void webLog() {

    }

    //请求method前打印内容
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容

        logger.info("===============请求内容 start===============");
        logger.info("请求地址URL : " + request.getRequestURL());
        logger.info("请求方式HTTP_METHOD : " + request.getMethod());
        logger.info("请求类方法:" + joinPoint.getSignature());
        logger.info("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
        logger.info("IP : " + request.getRemoteAddr());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            String p = request.getParameter(name);
            if (p != null) {
                if (p.length() > 500) {
                    p = p.substring(0, 500) + "...";
                }
            }
            logger.info("name:{},value:{}", name, p);
        }
        logger.info("===============请求内容 end=================");
    }

    /**在方法执行完结后打印返回内容*/
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        /**处理完请求，返回内容*/
        String r = objectMapper.writeValueAsString(ret);
        if (r != null) {
            if (r.length() > 500) {
                r = r.substring(0, 500) + "...";
            }
        }
        logger.info("返回内容Response:" + r);
    }
}

